package org.jgs1904.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 墨苍璃
 * @date 2022年06月29日20时28分
 * <p>
 * 第一个Shiro演示
 * <p>
 * 测试地址:
 * http://localhost:8080/userLogin?username=zhangsan&pwd=zs
 */
@Controller
public class DemoController {

    /**
     * 账号密码登录（认证）
     *
     * @param username
     * @param pwd
     * @return
     */
    @RequestMapping("/userLogin")
    @ResponseBody
    public String userLogin(String username, String pwd) {
        //1.获取SecurityManager对象
//        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//        SecurityManager securityManager = factory.getInstance();

        //DefaultSecurityManager 代替过时方法
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
        defaultSecurityManager.setRealm(iniRealm);

        //2.获取SubJect对象
//        SecurityUtils.setSecurityManager(securityManager);
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();
        //3.调用登录认证方法
        //创建对象存储认证信息
        AuthenticationToken token = new UsernamePasswordToken(username, pwd);
        //完成登录认证
        try {
            //login()方法没有返回值，只能通过是否有异常判断是否登录成功。
            subject.login(token);
            return "登录成功";
        } catch (UnknownAccountException e) {
            System.out.println("账号不存在");
            return "账号不存在";
        } catch (IncorrectCredentialsException e) {
            System.out.println("密码错误");
            return "密码错误";
        }
    }

}
